<template>
  <div class="win-cont" ref="outer">
    <div class="dragcont list">
      <el-row class="bline dragcont-head" ref="headEl">
        <span class="colspanmid" @dblclick="changeStore">代码</span>
        <span class="colspanmid" @dblclick="changeStore">名称</span>
        <span class="colspanmid" title="股票显示当前价格/基金显示今日收益浮动">股价</span>
        <span class="colspanmid">涨跌幅</span>
        <span class="colspanmid" v-if="isShowStore">持仓金额</span>
        <span class="colspanmid" v-if="isShowStore">已卖</span>
        <span class="colspanmid" v-if="isShowStore">盈亏金额</span>
        <span class="colspanmid" v-if="isShowStore">盈亏比例</span>
      </el-row>
      <div class="list bline">
        <el-row
          v-for="(item, idx) in topList"
          :key="idx"
          class="mt2"
          :class="getRateColor(item.f3)"
        >
          <span class="colspanname">{{ item.f12 }}</span>
          <span class="colspanmid">{{ item.f14 }}</span>
          <span class="colspanmid">{{ item.f2 }}</span>
          <span class="colspanmid">{{ item.f3 }}%</span>
        </el-row>
      </div>
      <div class="list bline">
        <el-row
          v-for="(item, idx) in showJJList"
          :key="idx"
          class="mt2"
          :class="getRateColor(item.rate)"
          
        >
          <div @dblclick="setNum(item)">
            <span class="colspanname">
              <!-- {{item.name}} -->
              <!-- <a target="_blank" :href="'http://fund.eastmoney.com/'+item.code+'.html?spm=search'">
                  <span class="fsize" :class="getRateColor(item.rate)">{{item.name}}</span>
              </a> -->
              
              <el-popover placement="right" :open-delay="500" trigger="hover" @show="item.showTimeLine=true" @hide="item.showTimeLine=false">
                  <div style="min-height:300px;display:flex;flex-direction:column;flex-wrap:nowrap">
                      <el-image style="width: 200px; height: 140px" v-if="item.showTimeLine" 
                        :src="`http://j4.dfcfw.com/charts/pic6/${item.code}.png?v=${rnd}`" fit="fill"></el-image>

                      <el-image style="width: 200px; height: 140px" v-if="item.showTimeLine" 
                        :src="`http://j3.dfcfw.com/images/JJJZ1/${item.code}.png?v=${rnd}`" fit="fill"></el-image>
                  </div>
                  <span style="text-decoration:underline" slot="reference">{{item.name}}</span>
              </el-popover>
            </span>

            <span class="colspanmid">
              <!-- {{ item.code }} -->
              <popList :code="item.code" :name="item.name" :fconfig="{realCode:'zcCode',code:'zcName',name:'ccRate',cur:'price',rate:'rate'}" sortBy="ccRate"
                        :url="'http://fund.10jqka.com.cn/web/fund/stockAndBond/++code++?'" :miniWin="true"
                    ></popList>
            </span>
            <span class="colspanmid"><span v-if="item.num">{{ item.diff }}</span></span>
            <span class="colspanmid">{{ item.rate }}%</span>
            <span class="colspanmid" v-if="isShowStore && item.num">{{(item.num * item.newprice).toFixed(0) |bigMoneyFormat}}</span>
            <span class="colspanmid" v-if="isShowStore && item.num">{{item.profit |bigMoneyFormat}}</span>
            <span class="colspanmid" v-if="isShowStore && item.num">{{(getTotalProfit(item)).toFixed(0) |bigMoneyFormat}}</span>
            <span class="colspanmid" v-if="isShowStore && item.num">{{getTotalProfitRate(item)}}</span>
          </div>
        </el-row>
        <el-row>
          
          <div :title="`持仓本金: ${bigMoneyFormat(sumJJBase)} 元\n预估利润: ${bigMoneyFormat(sumJJProfit)} 元`">
            <span class="colspanname" :class="getRateColor(sumJJProfit)">总金额</span>
            <span class="colspanmid" :class="getRateColor(sumJJProfit)">{{sumJJAmount+sumSaleProfit |bigMoneyFormat}}</span>
            <span class="colspanmid" :class="getRateColor(sumJJDiff)">今日浮动</span>
            <span class="colspanmid" :class="getRateColor(sumJJDiff)">{{sumJJDiff |bigMoneyFormat}}</span>
            <span class="colspanmid" v-if="isShowStore" :class="getRateColor(sumJJProfit)">{{sumJJAmount |bigMoneyFormat}}</span>
            <span class="colspanmid" v-if="isShowStore" :class="getRateColor(sumJJProfit)">{{sumSaleProfit}}</span>
            <span class="colspanmid" v-if="isShowStore" :class="getRateColor(sumJJProfit)">{{sumJJProfit |bigMoneyFormat}}</span>
            <span class="colspanmid" v-if="isShowStore" :class="getRateColor(sumJJProfit)">{{rateFormat(sumJJProfit,sumJJBase)}}</span>

            
          </div>
        </el-row>
      </div>
      <el-row
        v-for="(item, idx) in list"
        :key="idx"
        class="mt2"
        :class="getRateColor(item.r)"
      >
        <span class="colspanname">
          {{ item.c }}
          <!-- <klinePic :code="item.c" :name="item.n" :fclass="getRateColor(item.r)"></klinePic> -->
        </span>
        <span class="colspanmid">{{ item.n }}</span>
        <span class="colspanmid">{{ item.p }}</span>
        <span class="colspanmid">{{ item.r }}%</span>
      </el-row>
    </div>
    <exDialog
        @close="isShowWin = false"
        winName="设置数量"
        :visible.sync="isShowWin"
        :width="(250)+'px'"
        >
        <el-row>
          <exInput v-model="selItem.name" label="名称" size="mini" width="130"></exInput>
        </el-row>
        <el-row>
          <exInput v-model="selItem.num" label="数量" size="mini" width="130"></exInput>
        </el-row>
        <el-row>
          <exInput v-model="selItem.profit" label="已卖金额" size="mini" width="100"></exInput>
        </el-row>
        <el-row>
          <exInput v-model.number="selItem.baseamount" label="成本市值" size="mini" width="100" @keyup.native="changeBaseAmount(selItem)" @change="changeBaseAmount(selItem)"></exInput>
        </el-row>
        <!-- <el-row>
          <exInput v-model="selItem.baseprice" label="成本净值" size="mini" width="100"></exInput>
        </el-row> -->
        <el-row>
          成本净值: {{selItem.baseprice}} 元
        </el-row>
        <el-row>
          最新净值: {{selItem.newprice}} 元
        </el-row>
        <el-row>
          最新市值: {{(selItem.num * selItem.newprice).toFixed(0)}} 元
        </el-row>
        <el-row v-if="selItem.baseprice" >
          盈亏金额: <span :class="getRateColor(selItem.newprice-selItem.baseprice)">{{(selItem.num * selItem.newprice+(selItem.profit*1)-selItem.baseamount).toFixed(0)}} 元</span>
        </el-row>
        <el-row v-if="selItem.baseprice" >
          盈亏比例: <span :class="getRateColor(selItem.newprice-selItem.baseprice)">{{rateFormat(selItem.num * selItem.newprice+(selItem.profit*1)-selItem.baseamount,selItem.baseamount-(selItem.profit*1))}}</span>
        </el-row>
        <el-row>
          赎回金额: <exInput v-model="jjamount" width="100" size="mini"></exInput>
        </el-row>
        <el-row>
          赎回份额: {{(jjamount/selItem.newprice).toFixed(2)}} 份 
        </el-row>
        <el-row>
          剩余份额: {{selItem.num - (jjamount/selItem.newprice).toFixed(2)}} 份 
        </el-row>
        <el-row class="mt10">
          <el-button type="primary" @click="saveConfig" size="mini">保存</el-button>
        </el-row>
    </exDialog>
  </div>
</template>


<script>
import Vue from "vue";
import elementui from "~/plugins/element-ui";
import exfnInit from "~/plugins/exfnInit";
import popList from "./publist/popList"

import klinePic from "./comp/klinePic";

import timeLine from "@/components/chart/timeLine"
import kLine from "@/components/chart/kLine"

export default {
    components:{
        timeLine,
        kLine,
    klinePic,
    popList
  },
  layout: "default",
  data() {
    
    return {
      isLoad: false,
      jjamount : 1000,
      cfg: {
        favList: [],
        jjList : [],
      },
      topList: [],
      isShowWin : false,
      selItem : {},
      isWinMode : false,
      isShowStore : false,
      rnd: Math.random(),
    };
  },
  watch:{
      topList(){
          this.setWinSize();
      }
  },
  computed: {
    list() {
      var list = [].concat(this.cfg.favList);
      var tmplist = list.sort((a, b) => {
        if (!a.watch && !b.watch) return 0;
        if (a.watch && b.watch) return 1;
        if (a.watch) return -1;
        else return 1;
      });
      return tmplist || [];
    },
    showJJList(){
      this.cfg.jjList.sort((a,b)=>{
        if(a.num && !b.num){
          return -1
        }else if(!a.num && b.num){
          return 1;
        }else{
          var diff = a.num*a.newprice - b.num*b.newprice;
          if(diff>0){
            return -1
          }else if(diff<0){
            return 1
          }
          return 0;
        }
      });
      return this.cfg.jjList;
    },
    sumJJDiff(){
      if(!this.cfg.jjList) return 0;
      var total = 0;
      this.cfg.jjList.map(item=>{
        if(item.num>0){
          total += item.diff;
        }
      })
      return total.toFixed(1)*1;
    },
    sumJJAmount(){
      if(!this.cfg.jjList) return 0;
      var total = 0;
      this.cfg.jjList.map(item=>{
        if(item.num>0){
          total += item.num * item.newprice;
        }
      })
      
      if(!this.isShowStore && this.cfg.amountUnit){
        total = (total* this.cfg.amountUnit).toFixed(0)*1
        return total
      }
      return parseInt(total);
    },
    sumJJBase(){
      if(!this.cfg.jjList) return 0;
      var total = 0;
      this.cfg.jjList.map(item=>{
        if(item.baseamount>0){
          total += item.baseamount;
        }
      })
      if(!this.isShowStore && this.cfg.amountUnit){
        total = (total* this.cfg.amountUnit).toFixed(0)*1
        return total
      }
      return total
    },
    sumJJProfit(){
      if(!this.cfg.jjList) return 0;
      
      return (this.sumJJAmount+this.sumSaleProfit-this.sumJJBase).toFixed(0)*1
    },
    sumSaleProfit(){
      if(!this.cfg.jjList) return 0;
      var total = 0;
      this.cfg.jjList.map(item=>{
        if(item.profit){
          total += item.profit*1;
        }
      })
      if(!this.isShowStore && this.cfg.amountUnit){
        total = (total* this.cfg.amountUnit).toFixed(0)*1
        return total
      }
      return parseInt(total);
    }
  },

  mounted() {
    try{
      
      this.reLoad();
      this.setMove();
    }catch(ex){
      console.log(ex)
    }
  },
  methods: {
    changeStore(){
      this.isShowStore = !this.isShowStore;
      this.doQuery();
      this.setWinSize();
    },
    changeBaseAmount(item){
      item.baseprice = (item.baseamount/item.num).toFixed(4)*1;
    },
    getTotalProfit(item){  //盈亏金额
      var base = item.num * item.baseprice;
      var cur = item.num *item.newprice;
      if(item.profit) cur+=item.profit*1;
      return cur - base;
    },
    getTotalProfitRate(item){  //盈亏比例
      var base = item.num * item.baseprice;
      var cur = item.num *item.newprice ;
      // if(item.code=="011102"){
      //   debugger;
      // }
      if(item.profit) base-=item.profit*1;
      return this.rateFormat(cur-base,base)
    },
    setNum(item){
      this.selItem = item;
      this.isShowWin = true;
    },
    setWinSize(){
        if (!window.electron) return;
        
        var url = location.href;
        if(url.indexOf("popWin")==-1){
            return;
        }
        this.isWinMode = true;
        this.$nextTick(()=>{
            let win = electron.remote.getCurrentWindow();
            var arrsize = win.getSize();
            var el = this.$refs.outer;
            var height = el.scrollHeight;

            var isShowPrice = false;
            this.cfg.jjList.map(item=>{
              if(item.num>0){
                isShowPrice = true;
              }
            })
            var width= this.isShowStore? 500: 240;
            win.setSize(width,height);
            // win.setSize(20,30);
        })
    },
    setMove(){
        if (!window.electron) return;
        var url = location.href;
        if(url.indexOf("popWin")==-1){
            return;
        }
        let win = electron.remote.getCurrentWindow();
        let biasX = 0
        let biasY = 0
        let that = this;
        var headel = this.$refs.headEl.$el;
        headel.addEventListener('mousedown', function (e) {
            switch (e.button) {
                case 0:
                    biasX = e.x
                    biasY = e.y
                    headel.addEventListener('mousemove', moveEvent);
                break
                case 2:
                    // electron.ipcRenderer.send('createSuspensionMenu');
                break
            }
        })

        headel.addEventListener('mouseup', function () {
            biasX = 0
            biasY = 0
            headel.removeEventListener('mousemove', moveEvent)
        })

        function moveEvent(e) {
            win.setPosition(e.screenX - biasX, e.screenY - biasY)
        }
    },
    saveConfig(){
      var that = this;
      
      this.registerListen(this,"saveConfig",(err)=>{
          try{
              if(err){
                  that.$message.error("配置保存异常:"+err)
              }else{
                  that.isShowWin = false;
                  that.$message.success("保存成功")
              }
          }catch(ex){
                  that.$message.error("配置保存异常:"+err)
          }
      });
      
      electron.ipcRenderer.send("saveConfig",this.cfg)
    },
    reLoad() {
      var that = this;
      if (!window.electron) {
        that.isLoad = true;
        that.startTimer();
        that.setWinSize();
        return;
      }
      this.registerListen(this, "setConfig", (cfg) => {
        try {
          // console.info("loadCfg:" ,cfg)
          var cfg = JSON.parse(JSON.stringify(cfg));
          Object.assign(that.cfg, cfg);
          that.cfg.jjList.map(item=>{
            if(!item.num) item.num = 0;
            if(!item.baseprice) item.baseprice = 0;
            if(!item.baseamount) item.baseamount = 0;
            if(!item.diff) item.diff = 0;
            if(!item.profit) item.profit = 0;
            item.showTimeLine = false;
            this.changeBaseAmount(item)
          })

          that.isLoad = true;
          that.startTimer();
          that.setWinSize();
        } catch (ex) {
          that.$message.error("配置加载异常:" + ex.message);
        }
      });
      electron.ipcRenderer.send("getConfig", "");
    },
    doQuery() {
        
      this.getAllDetail();
      this.getTopInfo();
      this.getAllJJDetail();
    },
    startTimer() {
      this.doQuery();
      this.$once("hook:beforeDestroy", () => {
        clearTimeout(this.timer);
        clearInterval(this.topTimer);
      });
      this.doTimer();

    },
    doTimer() {
      clearTimeout(this.timer);
      this.rnd = Math.random()
      this.getAllDetail();

      var sleep = this.cfg.sleepTime || this.$config.defSleepTime;
      if (sleep < 1000 || isNaN(sleep)) sleep = this.$config.defSleepTime;

      this.timer = setTimeout(() => {
        this.doTimer();
      }, sleep);
    },
    getAllDetail() {
      let win = electron.remote.getCurrentWindow();
      var isshow = win.isVisible();
      console.info("isPopWinVisible:"+isshow)
      if(!isshow) return ;
      
      this.list.map((item) => {
        this.getDetail(item);
      });
      this.getTopInfo();
      this.getAllJJDetail();
    },
    getDetail(item) {
      var code = item.c;
      var that = this;
      var first = code.substring(0, 1);
      if (first == "0" || first == "3" || first == "1") {
        code = "0." + code;
      } else {
        code = "1." + code;
      }
      this.$axios
        .get(
          `http://push2.eastmoney.com/api/qt/stock/details/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54,f55&pos=-61&secid=${code}`
        )
        .then((res) => {
          if (res.data && res.data.data && res.data.data.details) {
            var datas = res.data.data.details;
            var prePrice = res.data.data.prePrice;
            var last = datas[datas.length - 1];
            if (!last && prePrice) {
              item.p = prePrice;
              item.r = 0;
              return;
            } else if (!last) {
              return;
            }
            var arr = last.split(",");
            item.p = arr[1];
            item.r = this.rateCount(arr[1] - prePrice, prePrice);
            item.r = item.r.toFixed(2);
            item.r = item.r * 1;
            item.prePrice = prePrice * 1;
          } else {
            if(this.isWinMode) return;
            this.$message.error(JSON.stringify(res.data));
          }
        });
    },
    getTopInfo() {
      this.$axios
        .get(
          `https://push2.eastmoney.com/api/qt/clist/get?pi=0&pz=10&po=1&np=1&fields=f1,f2,f3,f4,f12,f13,f14&fltt=2&invt=2&ut=13697a1cc677c8bfa9a496437bfef419&fs=i:1.000001,i:0.399001,i:0.399006`
        )
        .then((res) => {
          if (res.data.data) {
            this.topList = res.data.data.diff || [];
          } else {
            if(this.isWinMode) return;
            this.$message.error(res.data.message);
          }
        });
    },
    getAllJJDetail(){
        this.cfg.jjList.map((item)=>{
            if(item.code=="006327"){
              this.getJJDetail3(item);
            }else{
              this.getJJDetail(item);
            }
        });
    },
    getJJDetail2(item){
      this.$axios.post(`https://api.fund.eastmoney.com/favor/GetFundsInfo`,{fcodes:item.code})
      .then((res) => {
          try{
              if(res.data.Data){
                var list = res.data.Data.KFS;
                var data = null
                list.map(jj=>{
                  if(jj.FCODE==item.code){
                    data = jj;
                  }
                })
                if(!data) return;

                item.rate = data.RZDF*1;
                item.price = data.DWJZ*1;
                item.newprice = data.DWJZ*1;
                if(!item.name){
                    item.name = data.SHORTNAME.substring(0,6);
                }
                if(item.num){
                  item.diff = parseInt(item.num * (data.RZDE*1));
                }
              }
          }catch(ex){
            console.log("获取基金信息异常:")
            console.log(ex)
          }
      })
    },
    getJJDetail3(item){
      this.$axios.get(`https://fundsuggest.eastmoney.com/FundSearch/api/FundSearchAPI.ashx?m=9&key=${item.code}`)
      .then((res) => {
          try{
              if(res.data.Datas && res.data.Datas.length>0){
                var data = res.data.Datas[0].FundBaseInfo;
                
                item.rate = 0;
                item.price = data.DWJZ*1;
                item.newprice = data.DWJZ*1;
                if(!item.name){
                    item.name = data.SHORTNAME.substring(0,6);
                }
                if(item.num){
                  item.diff = 0;
                }
              }
          }catch(ex){
            console.log("获取基金信息异常:")
            console.log(ex)
          }
      })
    },
    getJJDetail(item){
        this.$axios.get(`http://fundgz.1234567.com.cn/js/${item.code}.js?`+Math.random())
        .then((res) => {
            try{
                res.data = res.data.substring(8,res.data.length-2) ;
                try{
                  res.data = JSON.parse(res.data);
                }catch(ex){
                  return;
                }
                item.rate = res.data.gszzl;
                item.price = res.data.dwjz*1;
                item.newprice = res.data.gsz*1;
                if(!item.name){
                    item.name = res.data.name.substring(0,6);
                }
                if(item.num){
                  item.diff = parseInt(item.num * (item.newprice-item.price));
                  if(!this.isShowStore && this.cfg.amountUnit){
                    item.diff = (item.diff* this.cfg.amountUnit).toFixed(2)*1
                  }
                }
            }catch(ex){
              console.log("获取基金信息异常:")
              console.log(ex)
              return;
              if(this.isWinMode) return;
                this.$message.error(ex.message);
            }
        })
    },
  },
};

</script>

<style lang="less">
.bline {
  border-bottom: 1px lightgray dotted;
}
.win-cont{
    position: relative;
    // pointer-events: none;
}
.dragcont-head:hover{
    background: lightgray;
    border-radius: 5px;
}
.list {
  font-size: 12px;
  line-height: 16px;
  min-width: 240px;
  .span-name {
    display: inline-block;
    min-width: 60px;
    text-align: center;
  }
  .span-price {
    display: inline-block;
    min-width: 60px;
    text-align: center;
  }
  .span-rate {
    display: inline-block;
    min-width: 40px;
    text-align: right;
  }

  .colspan {
    display: inline-block;
    min-width: 45px;
    text-align: center;
  }
  .colspanbigger {
    display: inline-block;
    min-width: 60px;
    text-align: center;
  }

  .colspanmid {
    display: inline-block;
    min-width: 55px;
    text-align: right;
  }
  .colspanname {
    display: inline-block;
    min-width: 60px;
    text-align: right;
  }
}
</style>
